<template>
  <el-row>
  	<!-- 树区 -->
  	<el-col class='mr20 userlist-tree' :xs='24' :sm='12' :md='12' :lg='6'>
  	   <el-input class='mt6 mb10'
  	      placeholder="输入关键字进行过滤"
  	      v-model.trim="filterText"  @focus='focusinput($event,1)'  @blur = 'blurinput($event,1)'>
  	   </el-input>
       <el-tree 
          :data="treedata"
     
          node-key="id"
          default-expand-all
          :default-expanded-keys='expandedKey'
          expand-on-click-node
          :filter-node-method="filterNode"
          ref="tree">
          <span class="custom-tree-node" slot-scope="{ node, data }" @mouseenter='mouseenter($event)' @mouseleave='mouseleave($event)'>

            <span>{{ data.name }}</span>
            <span class='vertical-middle option' style="visibility: hidden;">
              <el-button  v-if='permit.apart_check'  type="text" size="mini" title='查看' @click.stop="checkUsergroup(data.code)"> <i class='icon icon-look'></i></el-button>
              <el-button  v-if='permit.apart_edit' type="text" size="mini" title='编辑' @click.stop="editUsergroup(data.code)" style='margin-left:0;'> <i class='icon icon-edit'></i></el-button>
              <el-button  v-if='permit.apart_add' type="text" size="mini" title='添加' @click.stop="addUsergroup(data.name,data.code)" style='margin-left:0;'> <i class='icon icon-add'></i></el-button>
              <el-button  v-if='permit.apart_delete &&  data.parentCode != "rootroot"'  type="text" size="mini" title='删除'  @click.stop="() => remove(node, data)" style='margin-left:0;'> <i class='icon icon-delete'></i></el-button>
            </span>
          </span>
      </el-tree>
	</el-col>
	<el-col class='right-aside ' :xs='24' :lg='17'>
   <!--  搜索操作区 -->
    <el-row class="pb10 little-header">
          <el-col :lg='16'  align='left'>
                
                        <el-select v-model="search.useable" placeholder="请选择" class='w-30'>
                              <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                              </el-option>
                        </el-select>
                        <el-input class='w-40' placeholder='请输入登录名/角色/姓名' v-model.trim='search.name'  @focus='focusinput($event,2)'  @blur = 'blurinput($event,2)'></el-input>
                        <el-button icon="el-icon-search" type='primary' @click='userInit()'>搜索</el-button>
                
          </el-col>
          <el-col :lg='{span:6,offset:1}' >  
                <div align="right">
                        <el-button  v-if='permit.user_add'  type="primary" icon="el-icon-plus" size="small" round v-show="permission.add" @click="handleCreate()">新增</el-button>
                        <!-- <el-button  class='export-icon'               size="small" round  v-show="permission.add" @click="handleExport()"><i class='fa fa-share pr5'></i>导出</el-button> -->
                </div>
          </el-col>
    </el-row>
    <!-- table -->
    <el-table border  :data="tableList" class='w-100' :cell-class-name='hover' @cell-click='checkUser'>
          <el-table-column prop="loginName"       label="登录名"      align="center" class='activeCol'  fixed></el-table-column>
          <el-table-column prop="name"            label="姓名"        align="center"></el-table-column>
          <el-table-column prop="officeName"      label="部门"        align="center"></el-table-column>
          <el-table-column prop="position"        label="职位"        align="center">
                  <template  slot-scope='list'>
                          {{list.row.position | userPosition}}
                  </template>
          </el-table-column>
          <el-table-column prop="roleName"        label="角色"        align="center"></el-table-column>
          <el-table-column prop="useable"         label="状态"        align="center">
                  <template  slot-scope='list'>
                          <span v-if='list.row.useable == 1'>{{list.row.useable | userState}}</span>
                          <span v-else class='color-red'>{{list.row.useable | userState}}</span>
                  </template>
          </el-table-column>
          <el-table-column label="操作"                               align="center"  width="260"  v-if='permit.stop_user  ||  permit.user_edit  || permit.user_delete'>
                  <template v-slot="list"  >
                          <el-row  v-if='list.row.loginName == "system"'>
                              ——
                          </el-row>
                          <el-row  v-else>
                                 
                                        <el-button v-if="permit.stop_user && list.row.useable == '1'"   type="primary" size="mini" round @click="StopUser(list.$index, list.row)">停用</el-button>
                                        <el-button v-if="permit.stop_user && list.row.useable == '0'"   type="success" size="mini" round @click="StartUser(list.$index, list.row)">启用</el-button>
                                  
                                  <el-button v-if="permit.user_edit"   type="primary" size="mini" round @click="handleEdit(list.$index, list.row)">编辑</el-button>
                                  <el-button v-if="permit.user_delete" type="danger"  size="mini" round @click="handleDelete(list.$index, list.row)">删除</el-button>
                          </el-row>
                  </template>
          </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination class='mt28'
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="1"
            :page-sizes="[10, 20]"
            :page-size="10"
            :pager-count="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Total">
    </el-pagination>
  </el-col>
    <!-- 新增/编辑弹框 -->
    <Edit ref="formEdit" :parentList="parentList" v-on:save-finished="pageInit()"></Edit>
    <!-- 查看用户组信息 -->
    <CheckUserGroup ref="form_usergroup" :parentgroup="parentgroup" ></CheckUserGroup>
    <!-- 查看用户信息 -->
    <CheckUserList ref="form_userlist" :parentgroup="parentListgroup" ></CheckUserList>
    <!-- 编辑/添加用户组信息 -->
    <EditUserGroup ref="edit_usergroup" :parentgroup="parentEditgroup" :roleList='roleList' v-on:save-finished="treeInit()"></EditUserGroup>
    <!-- 编辑/添加用户信息 -->
    <EditUser ref="edit_user" :parentgroup="parentEditgroup" :roleList='roleList' :labelList='tagList'  v-on:save-finished="userInit()"></EditUser>
  </el-row>
  
</template>

<script>

//接口
import { listDepart,removeDepeart,getParentName ,listUser,removeUser,stopAUser,startAUser }  from  '@/api/user/index'
//     标签
import { listLabel } from '@/api/settings/label'
//      角色
import { listRole  } from '@/api/settings/index'

//*****组件***** 
//                新增/编辑
import  Edit  from '@/components/settings/labelEdit'
//                用户组详情查看
import  CheckUserGroup  from '@/components/userlist/CheckUserGroup'
//                用户详情查看
import  CheckUserList  from '@/components/userlist/CheckUserList'
//                编辑添加用户组
import  EditUserGroup  from '@/components/userlist/EditUserGroup'
//                编辑添加用户
import  EditUser  from '@/components/userlist/EditUser'

import { mapGetters } from 'vuex'

export default {
  name: 'userlist',
  data () {

    return {
      /*static*/
      /*当前用户允许权限*/
      permit:{
          //部门 增删改
          apart_check:false,//查看详情
          apart_delete:false,
          apart_add:false,
          apart_edit:false,
          //用户 增删改
          user_check:false,//查看详情
          user_delete:false,
          user_add:false,
          user_edit:false,

          //停用-启用 导出
          stop_user:false,
          export:false,
          
      },
      //查询 /初始化
      search: {
        name:this.Global.ie_nine == true ? '请输入登录名/角色/姓名':'',/*placeholder 兼容ie9 △*/
        useable:'',
        limit: 1000,
        currentPage:1,
      },
      search_place_str:'请输入登录名/角色/姓名',//placeholder输入内容 placeholder 兼容ie9 △

      tagSearch:{
        limit: 100,
        currentPage:1,
      },
      tagList:[],

      departSearch:{
        limit: 100,
        currentPage:1,
      },
      departList:[],

      userSearch:{
          limit: 10,
          currentPage:1,
      },

      roleList:[],


      showtree_child:true,//是否显示子节点用户 默认是
      expandAll:true,//控制子节点展开  默认展开
      expandedKey:[],//默认展开的节点设置  
      permission:{//表格允许操作
        add:true,
        edit:true,
        remove:true
      },
       options: [{
          value: '',
          label: '全部状态'
        }, {
          value: '1',
          label: '正常'
        }, {
          value: '0',
          label: '停用'
        }],

      treedata: [],//部门数 
      hoveractive:'hidden',
      filterText:this.Global.ie_nine == true ? '输入关键字进行过滤':'',/*placeholder 兼容ie9 △*/
      filterText_place_str:'输入关键字进行过滤',//placeholder输入内容 placeholder 兼容ie9 △
 

      tableList:[],// 列表data
      Total:null,//表格总页数

      //编辑data
      parentList:[],
      //查看用户组data
      parentgroup:[],
      //查看用户data
      parentListgroup:[],
      //编辑用户组data 传递给用户选择上级部门的部门树 list
      parentEditgroup:[],
      //编辑用户data
      parentEditUser:[],
    }
  },
  created() {
    this.pageall()//页面初始化，等待四个请求资源加载
  },
  methods:{
    //按顺序请求，并且能显示等待加载
    async pageall(){
        await this.pageInit()// 初始化 一次性请求使用资源
        await this.treeInit()//部门树 init
        this.jurisdiction()//初始化按钮权限操作
    },
    // 初始化 
    pageInit(){
        let that =this
        Promise.all([listLabel(this.tagSearch),listRole({limit: 100,currentPage:1}),listUser(this.userSearch)]).then((result) => {
            this.tagList = result[0].data.dataList/*listLabel*/
            this.roleList = result[1].data.dataList/*listRole*/
            this.tableList = result[2].data.dataList/*listUser*/
            this.Total= result[2].data.totalRs/*listUser*/
        }).catch((error) => {
            console.log(error)      
        })
    },
    //部门树 init
    treeInit(){
        let that=this
        /*请求部门树list  编辑新增  请求多次*/
        listDepart(this.search).then(res=>{
            if(res.data.flag == true){
                this.departList = res.data.dataList
                // this.formTree()
                let data = this.formTreeTest(this.departList)//写成通用的，因为添加部门时，需要添加用户 ，用户需要上级部门展示
                this.treedata=data//部门树
                this.parentEditgroup=data//传给组件的值
            }
        }).catch(error => {
            that.outputError(error)
        })
    },
    //用户list init
    userInit(){
        let that = this
        /*  编辑新增  会请求多次*/
        listUser(this.userSearch).then(res=>{
            if(res.data.flag == true){
                this.tableList = res.data.dataList
                this.Total=res.data.totalRs
            }
        }).catch(error => {
            that.outputError(error)
        }) 
    },
    //初始化按钮权限操作  40100
    jurisdiction(){
      
        this.permit.apart_check = this.button_limit.find(item => {
            return item.id === 40101
        })
        this.permit.apart_add = this.button_limit.find(item => {
            return item.id === 40102
        })
        this.permit.apart_edit = this.button_limit.find(item => {
            return item.id === 40103 
        })
        this.permit.apart_delete = this.button_limit.find(item => {
          return item.id === 40104 
        })

        this.permit.user_check = this.button_limit.find(item => {
          return item.id === 40105
        })
        this.permit.user_add = this.button_limit.find(item => {
          return item.id === 40106
        })
        this.permit.user_edit = this.button_limit.find(item => {
          return item.id === 40107
        })
        this.permit.user_delete = this.button_limit.find(item => {
          return item.id === 40108 
        })

        this.permit.stop_user = this.button_limit.find(item => {
          return item.id === 40109
        })
        this.permit.export = this.button_limit.find(item => {
          return item.id === 40111
        })
    },

    //查看用户组   
    checkUsergroup(code){
      //因为跟编辑时 请求上级部门名称 用的同一个接口
      let data ;
      getParentName(code).then(res=>{
          data=res.data.data
          this.$refs.form_usergroup.$emit('opencheck',data);
      })
    },
    //新增用户组
    addUsergroup(name,code){
        this.$refs.edit_usergroup.$emit('opengroup',name,code);
    },
    //编辑用户组
    editUsergroup(code){
        
        getParentName(code).then(res=>{
           let data=res.data.data
            this.$refs.edit_usergroup.$emit('openEditgroup',data,code);
        })
        
    },

  	append(data) {
        const newChild = {  label: 'testtest', children: [] };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },
      //删除部门
    remove(node, data) {
         let that=this;
          this.$confirm('确定删除该部门？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          })
          .then(() => {
              removeDepeart(data.code)
                .then(response => {
                    if(response.data.flag == true){
                        const parent = node.parent;
                        const children = parent.data.children || parent.data;
                        const index = children.findIndex(d => d.id === data.id);
                        children.splice(index, 1);
                        this.$message({type:'success',message:response.data.msg})
                    }
                })
                .catch(error => {
                    that.outputError(error)
                })
          })
          .catch(() => {})
    },
    filterNode(value, data) {
        // console.log(value,data)
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
    },
    

    /*新增 */
    handleCreate(){
        this.$refs.edit_user.$emit('openAddDialog') 
    },
    /*编辑 */
    handleEdit(index, row){
        let that =this
        this.$refs.edit_user.$emit('openEditDialog',row)
    },
    //删除
    handleDelete(index, row) {
        let that=this;
        this.$confirm('确定删除该条数据吗？', '提示', {  //删除确定弹框，公用
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        .then(() => {
            removeUser(row.code).then(response => {
                this.$message({type:'success',message: response.data.msg })
                this.userInit()
              })
              .catch(error => {
                that.outputError(error)
              })
        })
        .catch(() => {})  
    },
    
    //导出
    handleExport(){
        
    },

    /*每页显示条数变化 事件触发
     *@method 方法名
     *@for 所属类名
     *@param{val} 共几条
     *@return {} 
    */
    handleSizeChange(val) {
      this.userSearch.limit = val;
      this.userInit()
    },
    /*页数变化 事件触发
     *@method 方法名
     *@for 所属类名
     *@param{val} 第几页
     *@return {} 
    */
    handleCurrentChange(val) {
      this.userSearch.currentPage = val
      this.userInit()
    },
    mouseenter(e){
    	e.target.querySelector('.option').style.visibility=''
    	
    },
    mouseleave(e){
    	
    	e.target.querySelector('.option').style.visibility='hidden'
    	
    },

    /*placeholder 兼容ie9 focus-blur △*/
    focusinput(e,num){
        if(this.Global.ie_nine == true){
            /*bumentree filter*/
            if(num == 1){
                this.filterText = this.filterText == this.filterText_place_str ? '':this.filterText
            }
            if(num == 2){
                this.search.name = this.search.name == this.search_place_str ? '':this.search.name
            }
        }
    },
    blurinput(e,num){
        if(this.Global.ie_nine == true){
            let val = e.srcElement.value//ie9下只能用这个值
            if(num == 1){
                 this.filterText = val == '' ? this.filterText_place_str:val
            }
            if(num == 2){
                this.search.name = val == '' ? this.search_place_str:val
            }
        }
    },
    //用户列表登录名添加样式
    hover({row, column, rowIndex, columnIndex}){
    //console.log(row, column, rowIndex, columnIndex)
    //设置表格第一列的特殊样式  该样式需要在APP 或者 public.css设置
    if(columnIndex == 0  && this.permit.user_check){
      return 'activeCol'
    }
   },
   //点击表格第一列  查看用户详情
   checkUser(row, column, cell, event){
    // console.log(row)
        if(column.label == '登录名'  && this.permit.user_check){
            
                this.$refs.form_userlist.$emit('opencheck',row)
            
        }
   },
   //停用某个用户
   StopUser(index,row){
      let that=this;
      this.$confirm('确定停用该用户吗？', '提示', {  //删除确定弹框，公用
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        stopAUser(row.code)
          .then(response => {
            this.$message({type:'success',message:response.data.msg})
            this.userInit()
          })
          .catch(error => {
            that.outputError(error)
          })
      })
      .catch(() => {})
   },
   //启用某个用户
   StartUser(index,row){
      let that=this;
      
      this.$confirm('确定启用该用户吗？', '提示', {  //删除确定弹框，公用
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        

        startAUser(row.code)
          .then(response => {
            
            
            this.$message({type:'success',message:response.data.msg})
            this.userInit()
          })
          .catch(error => {
            
            that.outputError(error)
          })
      })
      .catch(() => {})
      
      
   },
   //子节点用户显示与否
   showtree_childChange(data){
    //如果子节点不显示
      if(data == false){
          console.log(this.$refs.tree.store.nodesMap)
        }
      else{
          // this.$refs.tree.store.nodesMap[2].expanded = true
      }
   }
  },
   watch: {
      filterText(val) {
          if(this.filterText == this.filterText_place_str){
              val=''
          }
          this.$refs.tree.filter(val);
      }
  },
  components:{
    Edit,
    CheckUserGroup,
    CheckUserList,
    EditUserGroup,
    EditUser,
  },
   computed:{
    ...mapGetters(['button_limit'])
  },
}
</script>


<style scoped>
.icon{width: 16px;height: 16px;padding-right: 5px;}
.icon-look{background: url('../../assets/images/img/option/icon-look.png') no-repeat;}
.icon-edit{background: url('../../assets/images/img/option/icon-edit.png') no-repeat;}
.icon-add{background: url('../../assets/images/img/option/icon-add.png') no-repeat;}
.icon-delete{background: url('../../assets/images/img/option/icon-delete.png') no-repeat;}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

/*@media(max-width: 1200px){
  .userlist-tree{width:40%;}
  .right-aside{width: 100%;margin-top:30px;}
}*/
</style>
